{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "8051735e",
   "metadata": {},
   "outputs": [],
   "source": [
    "import os\n",
    "\n",
    "os.environ['CUDA_VISIBLE_DEVICES'] = ''\n",
    "os.environ['TF_FORCE_GPU_ALLOW_GROWTH'] = 'true'"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "25e6bf7b",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'pretrain-mistral-191M/checkpoint-40600'"
      ]
     },
     "execution_count": 2,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "from transformers.trainer_utils import get_last_checkpoint\n",
    "\n",
    "latest = get_last_checkpoint(\"pretrain-mistral-191M\")\n",
    "latest"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "3cf6cad4",
   "metadata": {},
   "outputs": [],
   "source": [
    "from transformers import AutoTokenizer, AutoModelForCausalLM\n",
    "import torch"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "721ae957",
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "Special tokens have been added in the vocabulary, make sure the associated word embeddings are fine-tuned or trained.\n"
     ]
    }
   ],
   "source": [
    "tokenizer = AutoTokenizer.from_pretrained(latest)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "9f23c6cb",
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "Using sep_token, but it is not set yet.\n",
      "Using cls_token, but it is not set yet.\n",
      "Using mask_token, but it is not set yet.\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "PreTrainedTokenizerFast(name_or_path='pretrain-mistral-191M/checkpoint-40600', vocab_size=32000, model_max_length=1000000000000000019884624838656, is_fast=True, padding_side='right', truncation_side='right', special_tokens={'bos_token': '<s>', 'eos_token': '</s>', 'unk_token': '<unk>', 'pad_token': '<pad>', 'additional_special_tokens': ['<pad>', '<s>', '</s>', '<unk>']}, clean_up_tokenization_spaces=True),  added_tokens_decoder={\n",
       "\t0: AddedToken(\"<pad>\", rstrip=False, lstrip=False, single_word=False, normalized=False, special=True),\n",
       "\t1: AddedToken(\"<s>\", rstrip=False, lstrip=False, single_word=False, normalized=False, special=True),\n",
       "\t2: AddedToken(\"</s>\", rstrip=False, lstrip=False, single_word=False, normalized=False, special=True),\n",
       "\t3: AddedToken(\"<unk>\", rstrip=False, lstrip=False, single_word=False, normalized=False, special=True),\n",
       "}"
      ]
     },
     "execution_count": 5,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "tokenizer"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "df9d19b4",
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "/home/ubuntu/.local/lib/python3.10/site-packages/transformers/utils/generic.py:311: UserWarning: torch.utils._pytree._register_pytree_node is deprecated. Please use torch.utils._pytree.register_pytree_node instead.\n",
      "  torch.utils._pytree._register_pytree_node(\n",
      "/home/ubuntu/.local/lib/python3.10/site-packages/transformers/utils/generic.py:311: UserWarning: torch.utils._pytree._register_pytree_node is deprecated. Please use torch.utils._pytree.register_pytree_node instead.\n",
      "  torch.utils._pytree._register_pytree_node(\n"
     ]
    }
   ],
   "source": [
    "model = AutoModelForCausalLM.from_pretrained(latest)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "fc43bc71",
   "metadata": {},
   "outputs": [],
   "source": [
    "import time\n",
    "from tqdm import tqdm\n",
    "\n",
    "kwargs = {\n",
    "    'temperature': 0.9, \n",
    "    'max_new_tokens': 20, \n",
    "    'top_p': 0.95,\n",
    "    'repetition_penalty': 1.1, \n",
    "    'do_sample': True,\n",
    "    'num_beams': 1,\n",
    "}"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "id": "8a4f7b63",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "tensor([[0, 0, 0, 0, 0]])"
      ]
     },
     "execution_count": 8,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "inputs = tokenizer(['merupakan bekas Perdana Menteri Malaysia'], return_tensors='pt')\n",
    "generate_kwargs = dict(inputs)\n",
    "generate_kwargs = {**generate_kwargs, **kwargs}\n",
    "generate_kwargs.pop('token_type_ids', None)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "id": "cd9a008a",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "' merupakan bekas Perdana Menteri Malaysia.</s>'"
      ]
     },
     "execution_count": 9,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "o = model.generate(**generate_kwargs)\n",
    "tokenizer.decode(o[0])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "id": "6b880e78",
   "metadata": {},
   "outputs": [],
   "source": [
    "model = AutoModelForCausalLM.from_pretrained(latest, torch_dtype = torch.bfloat16)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "id": "f32445b1",
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "/home/ubuntu/.local/lib/python3.10/site-packages/transformers/utils/hub.py:700: UserWarning: The `organization` argument is deprecated and will be removed in v5 of Transformers. Set your organization directly in the `repo_id` passed instead (`repo_id={organization}/{model_id}`).\n",
      "  warnings.warn(\n"
     ]
    },
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "dd85d557700e4eaabad60152932e0d07",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "model.safetensors:   0%|          | 0.00/381M [00:00<?, ?B/s]"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "data": {
      "text/plain": [
       "CommitInfo(commit_url='https://huggingface.co/mesolitica/malaysian-mistral-191M-4096/commit/ab0fd768486521efe172e159f7fdeaa1b115e4f3', commit_message='Upload MistralForCausalLM', commit_description='', oid='ab0fd768486521efe172e159f7fdeaa1b115e4f3', pr_url=None, pr_revision=None, pr_num=None)"
      ]
     },
     "execution_count": 11,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "model.push_to_hub('malaysian-mistral-191M-4096', organization='mesolitica', safe_serialization=True)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "id": "3647d4ed",
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "/home/ubuntu/.local/lib/python3.10/site-packages/transformers/utils/hub.py:700: UserWarning: The `organization` argument is deprecated and will be removed in v5 of Transformers. Set your organization directly in the `repo_id` passed instead (`repo_id={organization}/{model_id}`).\n",
      "  warnings.warn(\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "CommitInfo(commit_url='https://huggingface.co/mesolitica/malaysian-mistral-191M-4096/commit/f33c65ed9585043cb16c012d7a95ad0a712312f6', commit_message='Upload tokenizer', commit_description='', oid='f33c65ed9585043cb16c012d7a95ad0a712312f6', pr_url=None, pr_revision=None, pr_num=None)"
      ]
     },
     "execution_count": 12,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "tokenizer.push_to_hub('malaysian-mistral-191M-4096', organization='mesolitica')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "7081b2fd",
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.10.12"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
